import { BrowserWindow } from 'electron'
import { MQTTService } from './mqttService'
import { MQTTIPCHandler } from './mqttIPCHandler'

// MQTT管理器类
export class MQTTManager {
  private static instance: MQTTManager | null = null
  private mqttService: MQTTService
  private ipcHandler: MQTTIPCHandler | null = null

  private constructor() {
    this.mqttService = new MQTTService()
  }

  // 单例模式
  static getInstance(): MQTTManager {
    if (!MQTTManager.instance) {
      MQTTManager.instance = new MQTTManager()
    }
    return MQTTManager.instance
  }

  // 初始化MQTT管理器
  initialize(mainWindow: BrowserWindow): void {
    // 设置主窗口引用
    this.mqttService.setMainWindow(mainWindow)
    
    // 创建IPC处理器
    this.ipcHandler = new MQTTIPCHandler(this.mqttService)
    
    console.log('MQTT管理器初始化完成')
  }

  // 获取MQTT服务实例
  getService(): MQTTService {
    return this.mqttService
  }

  // 清理资源
  cleanup(): void {
    if (this.ipcHandler) {
      this.ipcHandler.cleanup()
      this.ipcHandler = null
    }
    
    if (this.mqttService) {
      this.mqttService.disconnect()
    }
    
    console.log('MQTT管理器已清理')
  }
}
